//
//  NAvViewController.m
//  WKWebView
//
//  Created by admin on 2018/4/9.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "NAvViewController.h"

#import <WebKit/WebKit.h>

#import "WKDelegateController.h"

@interface NAvViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>

@property (nonatomic, strong) WKWebView *webView;

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UILabel *progressLabel;

@property (nonatomic, strong) UIProgressView *progress;

@property (nonatomic, strong) WKUserContentController *userContentController;

@end

@implementation NAvViewController

-(UIProgressView *)progress{
    if (_progress == nil) {
        _progress = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 2)];
        _progress.tintColor = [UIColor blueColor];
        _progress.backgroundColor = [UIColor lightGrayColor];
        [self.view addSubview:_progress];
    }
    return _progress;
}

-(WKWebView *)webView{
    if (!_webView) {
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]init];
        _userContentController = [[WKUserContentController alloc]init];
        configuration.userContentController = _userContentController;
        //注册方法
        WKDelegateController *delegateController = [[WKDelegateController alloc]init];
        delegateController.delegate = (id)self;
        [_userContentController addScriptMessageHandler:delegateController name:@"sayhello"];
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) configuration:configuration];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        _webView.allowsBackForwardNavigationGestures = YES;
//        [_webView loadRequest:[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baperp.com/HIDAppHelp/index.html"]]];
        
        [_webView loadRequest:[NSMutableURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15]];
        
        [self.view addSubview:_webView];
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    }
    return _webView;
}

-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
//    [NSString stringWithFormat:@"%@('%@');", @"callBack", [self getJsonWith:@{@"name":@"1",@"six":@"2"}]]
    if ([message.name isEqualToString:@"sayhello"]) {
        

    }
    NSMutableDictionary *dic = message.body[@"para"];
    NSLog(@"%@--%@--%@",dic,dic[@"name"],dic[@"six"]);
//    NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);
}

- (NSString*)getJsonWith:(NSDictionary*)dic {
    
    NSString *json = nil;
    
    if ([NSJSONSerialization isValidJSONObject:dic]) {
        
        NSError *error;
        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&error];
        
        if(!error) {
            
            json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            
        }
        
        else {
            
            NSLog(@"JSON parse error: %@", error);
            
        }
        
    }
    
    else {
        
        NSLog(@"Not a valid JSON object: %@", dic);
        
    }
    
    return json;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self webView];
    
    UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 100, 100, 100)];
    [btn1 setTitle:@"返回" forState:0];
    [btn1 setTitleColor:[UIColor redColor] forState:0];
    [btn1 addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc]initWithCustomView:btn1];
    
    UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(200, 100, 100, 100)];
    [btn2 setTitle:@"关闭" forState:0];
    [btn2 setTitleColor:[UIColor redColor] forState:0];
    [btn2 addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn2];
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithCustomView:btn2];
    
    self.navigationItem.leftBarButtonItems = @[item1,item2];
    
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 200, 100, 100)];
    [self.view addSubview:self.titleLabel];
    
    self.progressLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 300, 300, 100)];
    [self.view addSubview:self.progressLabel];
}

- (void)backAction{
//    if ([_webView canGoBack]) {
//        [_webView goBack];
//    }
    
    [_webView evaluateJavaScript:@"backToPre()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"%@",result);
    }];
    
//    [_webView evaluateJavaScript:@"say()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//        NSLog(@"%@",result);
//    }];

}

- (void)closeAction{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//监听代理
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        if (object == _webView) {
            [self.progress setAlpha:1.0f];
            [self.progress setProgress:_webView.estimatedProgress animated:YES];
            if (_webView.estimatedProgress >= 1.0f) {
                [UIView animateWithDuration:0.5f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                    [self.progress setAlpha:0.0f];
                } completion:^(BOOL finished) {
                    [self.progress setProgress:0.0f animated:NO];
                }];
            }
        }
        else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
}

-(void)dealloc{
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [_userContentController removeScriptMessageHandlerForName:@"sayhello"];
}

/// 2 页面开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    NSLog(@"开始");
}

/// 4 开始获取到网页内容时返回
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    self.progressLabel.text = [NSString stringWithFormat:@"%f",webView.estimatedProgress];
    NSLog(@"获取到了");
}

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    self.titleLabel.text = webView.title;
    self.progressLabel.text = [NSString stringWithFormat:@"%f",webView.estimatedProgress];
    NSLog(@"结束");
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"%s", __FUNCTION__);
    NSLog(@"%@",error);
} 

// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    NSLog(@"%@",message);
    completionHandler();
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
